
<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container">
      <div class="addbox">
        <el-button type="primary" @click="adduserVisible = true">添加用户</el-button>
        <!-- 添加角色对话框 -->
        <el-dialog v-model="adduserVisible" title="添加角色">
          <el-form
            :model="addjokerFrom"
            :label-width="100"
            class="demo-ruleForm"
            :rules="jokerroles"
            ref="addjokerFromref"
          >
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="addjokerFrom.name" type="text" />
            </el-form-item>
            <el-form-item label="角色描述" prop="details">
              <el-input v-model="addjokerFrom.details" type="text" />
            </el-form-item>
            <el-form-item>
              <el-button @click="adduserVisible = false">取消</el-button>
              <el-button type="primary" @click="addJokerOK(addjokerFromref)">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <!-- 表格主体 -->
      <el-table :data="jokerlist" style="width: 100%" border stripe size="large">
        <el-table-column prop="select" width="50" type="expand">
          <template #default="props">
            <div class="nullsay" v-if="!props.row.select.length">这个角色还没有被分配权限</div>
            <!-- 一级标签 -->
            <div class="innerTagbox" v-else v-for="(item, index) in props.row.select" :key="index">
              <div class="father">
                <el-tag
                  closable
                  size="large"
                  @close="deleteroles(props.row,item.id)"
                >{{ item.authName }}</el-tag>
                <el-icon>
                  <CaretRight />
                </el-icon>
              </div>
              <!-- 二级标签 -->
              <div class="children">
                <div class="childrentitle" v-for="(childrens, ind) in item.children" :key="ind">
                  <el-tag
                    closable
                    size="large"
                    @close="deleteroles(props.row,childrens.id)"
                    type="success"
                  >{{ childrens.authName }}</el-tag>
                  <el-icon>
                    <CaretRight />
                  </el-icon>
                  <!-- 三级标签 -->
                  <div class="son">
                    <el-tag
                      v-for="(son, i) in childrens.children"
                      :key="i"
                      closable
                      @close="deleteroles(props.row,son.id)"
                      size="large"
                      type="warning"
                    >{{ son.authName }}</el-tag>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="#" width="50" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="detail" label="角色描述" />
        <el-table-column prop="operation" label="操作">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" @click="edit(scope.row)">
              <el-icon>
                <EditPen />
              </el-icon>编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="deleteThere(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
            <el-button type="warning" @click="distributionThere(scope.row)">
              <el-icon>
                <Setting />
              </el-icon>分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <!-- <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="queryInfo.pagenum"
            v-model:page-size="queryInfo.pagesize"
            :page-sizes="[2, 5, 10, 15]"
            layout="total,sizes, prev, pager, next, jumper"
            :total="totals"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>-->
      <!-- 编辑对话框 -->
      <el-dialog v-model="editVisible" title="编辑角色信息">
        <el-form
          :model="editFrom"
          :label-width="100"
          class="demo-ruleForm"
          :rules="jokerroles"
          ref="editFromref"
        >
          <el-form-item label="角色名称" prop="username">
            <el-input v-model="editFrom.username" type="text" />
          </el-form-item>
          <el-form-item label="角色描述" prop="detail">
            <el-input v-model="editFrom.detail" type="text" />
          </el-form-item>
          <el-form-item label-width="770">
            <el-button @click="editVisible = false">取消</el-button>
            <el-button type="primary" @click="editThere(editFromref)">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog v-model="distributionVisible" title="分配权限" @close="setRightDialogClosed">
        <el-tree
          :data="treeRoles"
          check-on-click-node
          show-checkbox
          node-key="id"
          :props="defaultProps"
          default-expand-all
          ref="treeRef"
          :default-checked-keys="distributionList"
        />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="distributionVisible = false">取消</el-button>
            <el-button type="primary" @click="treeRolesThere(treeRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      distributionList: [],
      distributionVisible: false,
      treeRoles: [],
      rolesId: ""
    };
  },
  methods: {
    async distributionThere(item) {
      console.log(item);
      this.rolesId = item.id;
      const { data: res } = await getRights({ type: "tree" });
      this.treeRoles = res;

      await item.select.forEach(item => {
        this.getNodeKeyList(item, this.distributionList);
      });
      console.log(this.treeRoles, this.distributionList);
      this.distributionVisible = true;
    },
    getNodeKeyList(item, arr) {
      if (!item.children) {
        return arr.push(item.id);
      }
      item.children.forEach(item => this.getNodeKeyList(item, arr));
    },
    setRightDialogClosed() {
      this.distributionList = [];
    },
    treeRolesThere(tree) {
      let arr = [];
      arr.push(...tree.getHalfCheckedKeys(), ...tree.getCheckedKeys());
      postJokerRoles({
        id: this.rolesId,
        rids: arr.join(",")
      }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          ElMessage.success(res.meta.msg);
          this.distributionVisible = false;
          location.reload();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    }
  }
};
</script>
<script setup>
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { reactive, ref, onBeforeMount, onBeforeUpdate } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  puteditJoker,
  postAddJoker,
  deleteJoker,
  deleteJokerRoles,
  putUserRole,
  getUserRoles,
  getRights,
  postJokerRoles
} from "../tools/ajax.js";
const route = useRoute();
const router = useRouter();
// const treeRoles = reactive([]);
const treeRef = reactive({});
const userRolelist = reactive([]);
const addjokerFromref = reactive({});
const editFromref = reactive({});
const jokerlist = reactive([]);
const adduserVisible = ref(false);
const editVisible = ref(false);
const addjokerFrom = reactive({
  name: "",
  details: ""
});
const roleId = ref("");
const editFrom = reactive({
  id: "",
  username: "",
  detail: ""
});
const queryInfo = reactive({
  query: "",
  // 当前页数
  pagenum: 1,
  // 每页显示多少数据
  pagesize: 5
});
// const totals = ref(0);

const jokerroles = {
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: "change"
    },
    {
      min: 2,
      max: 6,
      message: "账号长度在2-6位之间",
      trigger: "change"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change"
    },
    {
      min: 4,
      max: 12,
      message: "密码长度在4-12位之间",
      trigger: "change"
    }
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "change"
    }
  ],
  mobile: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change"
    }
  ],
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change"
    }
  ],
  details: [
    {
      required: true,
      message: "请输入描述",
      trigger: "change"
    }
  ]
};
function getlist() {
  getUserRoles().then(res => {
    jokerlist.splice(0, 1000);
    res.data.forEach((item, index) => {
      jokerlist.push({
        select: item.children,
        num: index + 1,
        name: item.roleName,
        detail: item.roleDesc,
        id: item.id
      });
    });
  });
}
// 修改用户状态
function statuschange(item) {
  console.log(item.status, item.operation);
  putUserStatus({
    id: item.operation,
    status: item.status
  }).then(res => {
    console.log(res);
    if (res.meta.status == 200) {
      ElMessage.success(res.meta.msg);
    } else {
      ElMessage.error(res.meta.msg);
    }
  });
}
function handleSizeChange() {
  console.log("每页条数改变了");
  getlist();
}
function handleCurrentChange() {
  console.log("页面改变了");
  getlist();
}
function search() {
  console.log("搜索执行了");
  getlist();
}

// 添加用户
function addJokerOK(from) {
  from.validate(flag => {
    if (flag) {
      console.log(addjokerFrom);
      postAddJoker({
        roleName: addjokerFrom.name,
        roleDesc: addjokerFrom.details
      }).then(res => {
        console.log(res);
        if (res.meta.status == 201) {
          ElMessage.success(res.meta.msg);
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
      adduserVisible.value = false;
    } else {
      return;
    }
  });
}

// 编辑信息
function editThere(from) {
  console.log(editFrom);
  from.validate(flag => {
    if (flag) {
      puteditJoker({
        id: editFrom.id,
        roleName: editFrom.username,
        roleDesc: editFrom.detail
      }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          ElMessage.success(res.meta.msg);
          editVisible.value = false;
          getlist();
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    } else {
      return;
    }
  });
}
function edit(item) {
  console.log(item);
  editVisible.value = true;
  editFrom.username = item.name;
  editFrom.detail = item.detail;
  editFrom.id = item.id;
}

// 删除用户
function deleteThere(item) {
  console.log(item);
  ElMessageBox.confirm("此操作将永久删除该角色,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteJoker({ id: item.id }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          getlist();
          ElMessage.success(res.meta.msg);
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
}

// 分配
const defaultProps = {
  children: "children",
  label: "authName"
};
// vue3 依托答辩
// const distributionThere = async item => {
// getRights({ type: "tree" }).then(res => {
//   if (res.meta.status == 200) {
//     treeRoles.splice(0, 1000);
//     treeRoles.push(...res.data);
//     item.select.forEach(item => {
//       getNodeKeyList(item, distributionList);
//     });
//     console.log(distributionList);
//     distributionVisible.value = true;
//   } else {
//     ElMessage.error("权限获取失败");
//   }
// });
// }

function distributionThereOK() {
  console.log(distributionFrom);
  if (distributionFrom.newjoker) {
    putUserRole({
      id: distributionFrom.id,
      rid: distributionFrom.newjoker
    }).then(res => {
      console.log(res);
      if (res.meta.status == 200) {
        ElMessage.success(res.meta.msg);
        distributionVisible.value = false;
        getlist();
      } else {
        ElMessage.error(res.meta.msg);
      }
    });
  } else {
    ElMessage.error("请选择需要分配的角色");
  }
}
// 移除指定权限
function deleteroles(item, params) {
  console.log(item, params);
  ElMessageBox.confirm("此操作将移除该用户的权限,是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteJokerRoles({
        roleId: item.id,
        rightId: params
      }).then(res => {
        console.log(res);
        if (res.meta.status == 200) {
          item.select = res.data;
          ElMessage.success(res.meta.msg);
        } else {
          ElMessage.error(res.meta.msg);
        }
      });
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
}
onBeforeMount(() => {
  getlist();
});
</script>

<style scoped>
.addbox {
  margin-bottom: 20px;
  display: flex;
}
/* .pagination {
  margin-top: 20px;
} */
/* .input-with-select {
  width: 400px;
  height: 40px;
} */
.addbox > .el-button.el-button--primary {
  height: 40px;
}

.innerTagbox,
.nullsay {
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.father {
  width: 10%;
}
.children {
  width: 90%;
}
.childrentitle {
  display: flex;
  align-items: center;
  height: 60px;
  border-bottom: 1px #ebeef5 solid;
}
.son {
  margin-left: 50px;
}
.son .el-tag {
  margin-left: 20px;
}
</style>